package com.sinosoft.call.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sinosoft.call.SpringContext;
import com.sinosoft.call.entity.CallConfig;
import com.sinosoft.call.entity.CallIndex;
import com.sinosoft.call.service.BaseCallService;
import com.sinosoft.call.service.CallService;
import com.sinosoft.enums.http.StatusCode;
import com.sinosoft.utils.date.TimeUtil;
import com.sinosoft.utils.logback.LogUtil;
import com.sinosoft.utils.xml.XmlUtil;
import com.sinosoft.vo.http.Result;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.cloud.context.config.annotation.RefreshScope;

@Service
@RefreshScope
public class BaseCallServiceImpl implements BaseCallService{
    
    
	/**配置对象**/
	private static Map<String,CallConfig> _WEBSERVER= null;
	private static final String _YES="1";
	@SuppressWarnings("unused")
	private static final String _NO="0";
	/**URL请求超时标识 **/
	public static final String TIMEOUT = "TIMEOUT";
	/**无数据 标识 **/
	public static final String NODATA = "NODATA";
	/**请求失败 标识**/
	public static final String RQUESTERRO = "RQUESTERRO";
	@Override
	public Result callService(String serviceCode, JSON param, CallIndex ci) {
		Result re = pubResultJSON(false,"callWebService",null);
		//得对应的 callConfig 配置
		CallConfig callConfig =ci.getCallindex().get(serviceCode); 
		if(callConfig!=null&&_YES.equals(callConfig.getState())){
			//校验服务是否停用
			String message = this.checkServiceTime(callConfig);
			if(StringUtils.isNotBlank(message)){
				re= pubResultJSON(false,message,"");
			}else{
				CallService call = getCallService(callConfig);
				re = call.callService(callConfig, param);
			}
			
		}else if (callConfig!=null&&"2".equals(callConfig.getState())){//为模拟数据测试
			re = getFormatResponseXML(callConfig.getResponsestr(),serviceCode,callConfig.getPrintflag());
		}else{
			re= pubResultJSON(false,"无效的WebService服务",null);
		}
		//LogUtil.business(re.toJSONString());
		return  re;
	
	}

	/**得到配置服务
	 * @param callConfig
	 * @return
	 */
	private CallService getCallService(CallConfig callConfig) {
		CallService re = null;
		switch (callConfig.getRequesttype()) {
		case "AXIS":
			re = SpringContext.getBean("axisCallService");
			break;
		case "REST":
			re = SpringContext.getBean("restCallService");
			break;	
		default:
			re = SpringContext.getBean(callConfig.getRequesttype().toLowerCase()+"CallService");
			break;
		}
		
		return re;
	}

        
	/**公用组装JOSN
	 * @param result 状态
	 * @param info 信息
	 * @param data 数据
	 * @return {Success:状态,Message:信息,Data:数据}
	 * @author zouren
	 */
	public Result pubResultJSON(boolean result,String info,Object data){
                if(result) {
                    return Result.ok().setData(data);
                }else {
                    Result e = Result.failure(StatusCode.FAILURE);
                    e.setMsg(info);
                    return e;
                }

	}
	/**
	 * 返回报文统一处理 结果
	 * 
	 * @param responseStr
	 *            返回报文
	 * @param serviceCode   对应WsdlConfig表中的code
	 * @param printflag   对应WsdlConfig表中的printflag(1 不打印响应报文) 
	 *         
	 * @return 结果 {Success:true为成功，false为失败,Message:提示信息}
	 * @author zouren
	 */
	protected Result getFormatResponseXML(String responseStr,
			String serviceCode,String printflag) {

		Result result = null;
//		LogUtil.business("serviceCode:{},响应报文::{}", serviceCode,responseStr);
		String logMassage;
//		try {
//			responseStr = URLDecoder.decode(responseStr, "utf-8");
//		} catch (Exception e) {
//
//		}
		if (StringUtils.isBlank(responseStr)) {
			result = pubResultJSON(false, "暂无数据!", null);
			logMassage = "返回空,serviceCode:" + serviceCode;
		} else if (TIMEOUT.equals(responseStr)) {
			result = pubResultJSON(false, "系统请求超时!", null);
			logMassage = "超时标识 ,serviceCode:" + serviceCode;
		} else if (NODATA.equals(responseStr)) {
			result = pubResultJSON(false, "系统无数据!", null);
			logMassage = "无数据,serviceCode:" + serviceCode;
		} else if (RQUESTERRO.equals(responseStr)) {
			result = pubResultJSON(false, "系统请求失败!", null);
			logMassage = "请求失败,serviceCode:" + serviceCode;
		} else {
			// 避免结果解析异常
			responseStr = responseStr.replaceAll(
					"<!DOCTYPE TCRMService SYSTEM  \"tCRMResponse.dtd\">", "");
			// 处理BO返回错误
			responseStr = responseStr.replaceAll("><!--", ">");
			responseStr = responseStr.replaceAll("--><", "<").trim();
			JSON jso = null;
			if (responseStr.startsWith("{")) {// JSON对象字串
				jso = JSONObject.parseObject(responseStr);
			} else {// XML
				try {
					jso = XmlUtil.documentToJSONObject(responseStr);
				} catch (DocumentException e) {
					e.printStackTrace();
				}
			}
			result = pubResultJSON(true, "获取数据成功", jso);
			logMassage = jso.toString();
		}
		if("1".equals(printflag)){
			LogUtil.business("响应报文不打印 ,serviceCode:{}", serviceCode);
		}else{
			LogUtil.business("serviceCode:{}  响应报文:{}", serviceCode,logMassage);
		}
		
		return result;
	}
	
	
	
	/**
	 * 校验服务停用时间
	 * 
	 * @param callConfig
	 * @return "" 或提示信息
	 */
	private String checkServiceTime(CallConfig callConfig){
		
		String message = "";
		
		String startTime = callConfig.getStarttime();//服务停用开始时间
		String endTime = callConfig.getEndtime();//服务停用结束时间
		String proMessage = callConfig.getPromessage();//提示信息
		
		if(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime) && StringUtils.isNotBlank(proMessage)){
			try{
				startTime = startTime.replaceAll(":", "").trim();//服务停用开始时间
				endTime = endTime.replaceAll(":", "").trim();//服务停用结束时间
				
				String nowTime = TimeUtil.getCurrentDateString("HHmm");
				int hour = Integer.parseInt(nowTime);
				int iStrat = Integer.parseInt(startTime);
				int iend = Integer.parseInt(endTime);
				
				if(hour >= iStrat && hour <= iend){
					JSONObject paraMap = new JSONObject();
					paraMap.put("startTime", callConfig.getStarttime().trim());
					paraMap.put("endTime", callConfig.getEndtime().trim());
					
					message = getMassage(proMessage, paraMap);
				}
				
				
			}catch (Exception e) {
				
			}
		}
		
		return message;
		
	}
	/**
	 * @param massageTemplet 信息模板
	 * @param map 替换的参数据  使用 map中的#+key+# 来定位massageTemplet文件的位置  并使用value替换
	 * @return 替换后的信息
	 * @author zouren
	 */
	public static String getMassage(String massageTemplet,JSONObject map){
		String re ="";
		if(massageTemplet!=null&&map!=null&&map.size()>0){
			re = massageTemplet;
			Iterator<Entry<String, Object>> it =map.entrySet().iterator();
			while(it.hasNext()){
				Entry<String, Object> row= it.next();
				re = re.replace("#"+row.getKey()+"#", row.getValue()!=null?row.getValue().toString(): "");
			}
		}
		return re;
	}
	
	public static void main(String[] args) {
		JSONObject aa = new JSONObject();
		aa.put("b", "aaa");
		aa.put("aaaa", "1111");
		aa.put("c", "222");
	}
	 

}
